﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Compiled_Tests.Utils;
using System.Windows.Automation;
using System.Diagnostics;
using LEET.CommonInterfaces.TestControls;
using System.Windows;

namespace Compiled_Tests
{
    public class DemoController : BaseController, IController
    {

        IStepper stepper;
        StepperFactory factory;
        bool atBreakPoint;
        
        public DemoController(ITestScript script) : base(script)
        {
            factory = createStepperDialog;
            atBreakPoint = true;

            SignalRecieved += HandleWait;
        }

        public delegate IStepper StepperFactory();
        public DemoController(ITestScript script, StepperFactory factory) : this(script)
        {
            this.factory = factory;
        }

        private IStepper createStepperDialog()
        {
            StepDialog w = new StepDialog();
            w.SizeToContent = SizeToContent.WidthAndHeight;
            w.ResizeMode = ResizeMode.NoResize;
            w.StepButton.Focus();
            return w;
        }

        public override void Run()
        {
            FireEvent(new AutomationActionResult(initial));
            stepper = factory();
            stepper.OnStep += RunToBreakPoint;
            stepper.Run();
        }

        private void HandleWait(ScriptSignal s){
            if(s.Equals(ScriptSignal.Wait))
            {
                atBreakPoint = true;
                stepper.Break();
            }
        }

        private void RunToBreakPoint(){
            try
            {
                atBreakPoint = false;
                while (!atBreakPoint && Actions.MoveNext())
                {
                    IAutomationActionResult result = Actions.Current;
                    FireEvent(result);
                }
                if (!atBreakPoint)
                {
                    stepper.Dispose();
                    ShutDown();
                }
            }
            catch (Exception e)
            {
                stepper.Dispose();
                ShutDown();
                Window w = stepper as Window;
                if(w != null)
                    MessageBox.Show(w, e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                throw e;
            }
        }
        
    }
}
